package com.jyw.business.router.impl;

import com.alibaba.fastjson2.JSONObject;
import com.jyw.business.router.IRouterMpCodeService;
import com.jyw.business.router.domain.dto.CreateWxCodeDto;
import com.jyw.common.constant.ConfigKeyConstant;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.exception.ServiceException;
import com.jyw.system.domain.dto.HospitalApiRequest;
import com.jyw.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 调用分发器小程序码实现功能
 */
@Service
@Slf4j
public class RouterMpCodeServiceImpl implements IRouterMpCodeService {
    @Resource
    private ISysConfigService configService;

    @Resource
    private RestTemplate restTemplate;

    @Override
    public String createMpCode(String type,String id,String page) {
        HospitalApiRequest request = JSONObject.parseObject(configService.selectConfigByKey(ConfigKeyConstant.HOSPITAL_ROUTER_SECRET), HospitalApiRequest.class);

        String envVersion = configService.selectConfigByKey(ConfigKeyConstant.CODE_ENV_VERSION);

        CreateWxCodeDto dto = new CreateWxCodeDto(request,type,id,page,envVersion);
        if(dto.getScene().length()>32){
            throw new ServiceException("scene长度不能超过32位");
        }
        try {
            ResponseEntity<CommonResult> response = restTemplate.postForEntity(
                    configService.selectConfigByKey(ConfigKeyConstant.JYW_ROUTER_URL) + "/wx/miniapp/code",
                    dto,
                    CommonResult.class
            );
            CommonResult body = response.getBody();
            log.info("向分发器请求小程序码,返回信息:{}", body);
            if(body.getCode()!=200){
                throw new ServiceException("向分发器请求小程序码失败");
            }
            return (String) body.getData();
        }catch (Exception e){
            throw new ServiceException("向分发器请求小程序码失败");
        }
    }
}
